package com.cc.cbdb.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.cc.cbdb.R;
import com.cc.cbdb.common.constants.Constant;
import com.cc.cbdb.common.utils.SPUtil;
import com.cc.cbdb.entity.AppointmentTypeCodes;
import com.cc.cbdb.entity.BiogAddrCodes;
import com.cc.cbdb.entity.BiogInstCodes;
import com.cc.cbdb.entity.ChoronymCodes;
import com.cc.cbdb.entity.Dynasties;
import com.cc.cbdb.entity.OfficeCategories;
import com.cc.cbdb.entity.TextRoleCodes;
import com.cc.cbdb.common.utils.NetRequest;
import com.cc.cbdb.common.utils.StringUtil;
import com.cc.cbdb.common.utils.ToastUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Request;

public class AdvancedQueryActivity extends AppCompatActivity implements View.OnClickListener{

    private static final String TAG = "AdvancedQueryActivity";

    private Context mContext;

    private TextView tv_choronym,tv_dy,tv_addrType,tv_appointmentType,tv_offCategory,tv_biogInst;
    private EditText et_name,et_enthnicity,et_addrName,et_officeName,et_entryType,et_institution,et_textName,et_status;
    private Spinner sp_textRole;

    private Map<Integer,AlertDialog> mDialogs;
    //多选中选中的ID
    private Map<Integer,List<Integer>> mSelecteds;
    //5个单选的ID
    private String[] mSingleSelectIds = new String[6];

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_advanced_query);
        mContext = this;
        initUI();
        initData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SPUtil.clear(this);
    }

    private void initUI() {
        et_addrName = findViewById(R.id.et_addrName);
        et_enthnicity = findViewById(R.id.et_enthnicity);
        et_institution = findViewById(R.id.et_institution);
        et_name = findViewById(R.id.et_name);
        et_officeName = findViewById(R.id.et_officeName);
        et_entryType = findViewById(R.id.et_entryType);
        et_textName = findViewById(R.id.et_textName);
        et_status = findViewById(R.id.et_status);

        tv_choronym = findViewById(R.id.tv_choronym);
        tv_dy = findViewById(R.id.tv_dy);
        tv_addrType = findViewById(R.id.tv_addrType);
        tv_appointmentType = findViewById(R.id.tv_appointmentType);
        tv_offCategory = findViewById(R.id.tv_offCategory);
        tv_biogInst = findViewById(R.id.tv_biogInst);

        Spinner sp_female = findViewById(R.id.sp_female);
        sp_textRole = findViewById(R.id.sp_textRole);

        Button btn_query = findViewById(R.id.btn_query);
        Button btn_clean = findViewById(R.id.btn_clean);

        String[] females = {"请选择","男","女"};
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.support_simple_spinner_dropdown_item, females);
        sp_female.setAdapter(adapter);
        sp_female.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                if (i == 1){
                    mSingleSelectIds[0] = "0";
                }else if (i == 2){
                    mSingleSelectIds[0] = "1";
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        tv_choronym.setOnClickListener(this);
        tv_dy.setOnClickListener(this);
        tv_addrType.setOnClickListener(this);
        tv_appointmentType.setOnClickListener(this);
        tv_offCategory.setOnClickListener(this);
        tv_biogInst.setOnClickListener(this);

        et_enthnicity.setOnClickListener(this);
        et_addrName.setOnClickListener(this);
        et_officeName.setOnClickListener(this);
        et_entryType.setOnClickListener(this);
        et_institution.setOnClickListener(this);
        et_status.setOnClickListener(this);

        btn_query.setOnClickListener(this);
        btn_clean.setOnClickListener(this);
    }

    private void initData(){
        mSelecteds = new HashMap<>();
        mDialogs = new HashMap<>();
        for (int i = 0; i < 9; i++) {
            mSelecteds.put(i,new ArrayList<Integer>());
        }

        getAsyncData(Constant.URL.URL_QUERYCHORONYM,0);
        getAsyncData(Constant.URL.URL_QDYALL,1);
        getAsyncData(Constant.URL.URL_QADDRTYPES,2);
        getAsyncData(Constant.URL.URL_QAPPOINTMENT,3);
        getAsyncData(Constant.URL.URL_QOFFCATEGORY,4);
        getAsyncData(Constant.URL.URL_QBIOGINST,5);
        getAsyncData(Constant.URL.URL_QTEXTROLE,6);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        String checkedIds = null;
        String param1 = null;
        String param2 = null;
        if (data != null){
            checkedIds = data.getStringExtra("checkedIds");
            param1 = data.getStringExtra("param1");
            param2 = data.getStringExtra("param2");
        }
        switch (resultCode){
            case 1:
                if (StringUtil.isNotNull(checkedIds)){
                    et_enthnicity.setText("已选择"+splitStr(mSelecteds.get(6),checkedIds)+"项");
                }else {
                    et_enthnicity.setText("");
                }
                break;
            case 2:
                et_addrName.setText(param2);
                if (param1 != null)
                    mSingleSelectIds[1] = param1;
                    break;
            case 3:
                et_officeName.setText(param2);
                if (param1 != null){
                    mSingleSelectIds[2] = param1;
                    mSingleSelectIds[5] = data.getStringExtra("param3");
                }
                break;
            case 4:
                et_entryType.setText(param2);
                if (param1 != null)
                    mSingleSelectIds[3] = param1;
                break;
            case 5:
                if (StringUtil.isNotNull(checkedIds)){
                    et_institution.setText("已选择"+splitStr(mSelecteds.get(7),checkedIds)+"项");
                }else {
                    et_institution.setText("");
                }
                break;
            case 6:
                if (StringUtil.isNotNull(checkedIds)){
                    et_status.setText("已选择"+splitStr(mSelecteds.get(8),checkedIds)+"项");
                }else {
                    et_status.setText("");
                }
                break;
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    private int splitStr(List<Integer> integers,String checkedIds) {
        String[] split = checkedIds.split(",");
        for (int i = 0; i < split.length; i++) {
            integers.add(Integer.parseInt(split[i]));
        }
        return split.length;
    }

    private void getAsyncData(String url, final int index){
        NetRequest.getFormRequest(Constant.DOMAIN_PROJECT+url,null,new NetRequest.DataCallBack(){
            @Override
            public void requestSuccess(String result) throws Exception {
                Log.d(TAG,"json返回数据："+result);

                switch (index){
                    case  0:
                        List<ChoronymCodes> list1 = new Gson().fromJson(result, new TypeToken<List<ChoronymCodes>>(){}.getType());
                        int listSize1 = list1.size();
                        String[] names1 = new String[listSize1];
                        int[] ids1 = new int[listSize1];
                        for (int i = 0; i <listSize1 ; i++) {
                            StringBuilder sb = new StringBuilder(list1.get(i).getcChoronymDesc());
                            sb.append(" ");
                            sb.append(list1.get(i).getcChoronymChn());
                            names1[i] = sb.toString();
                            ids1[i] = list1.get(i).getcChoronymCode();
                        }
                        mDialogs.put(index,buildDialogMoreChoice(names1, ids1,tv_choronym,mSelecteds.get(index),"郡望"));
                        break;

                    case 1:
                        List<Dynasties> list2 = new Gson().fromJson(result, new TypeToken<List<Dynasties>>(){}.getType());
                        int listSize2 = list2.size();
                        String[] names2 = new String[listSize2];
                        int[] ids2 = new int[listSize2];
                        for (int i = 0; i <listSize2 ; i++) {
                            StringBuilder sb = new StringBuilder(list2.get(i).getcDynastyChn());
                            sb.append("(");
                            sb.append(list2.get(i).getcStart());
                            sb.append("-");
                            sb.append(list2.get(i).getcEnd());
                            sb.append(")");
                            names2[i] = sb.toString();
                            ids2[i] = list2.get(i).getcDy();
                        }
                        mDialogs.put(index,buildDialogMoreChoice(names2, ids2,tv_dy,mSelecteds.get(index),"朝代"));
                        break;

                    case 2:
                        List<BiogAddrCodes> list3 = new Gson().fromJson(result, new TypeToken<List<BiogAddrCodes>>(){}.getType());
                        int listSize3 = list3.size();
                        String[] names3 = new String[listSize3];
                        int[] ids3 = new int[listSize3];
                        for (int i = 0; i <listSize3 ; i++) {
                            names3[i] = list3.get(i).getcAddrDescChn();
                            ids3[i] = list3.get(i).getcAddrType();
                        }
                        mDialogs.put(index,buildDialogMoreChoice(names3, ids3,tv_addrType,mSelecteds.get(index),"地址类别"));
                        break;

                    case 3:
                        List<AppointmentTypeCodes> list4 = new Gson().fromJson(result, new TypeToken<List<AppointmentTypeCodes>>(){}.getType());
                        int listSize4 = list4.size();
                        String[] names4 = new String[listSize4];
                        int[] ids4 = new int[listSize4];
                        for (int i = 0; i <listSize4 ; i++) {
                            names4[i] = list4.get(i).getcApptTypeDescChn();
                            ids4[i] = list4.get(i).getcApptTypeCode();
                        }
                        mDialogs.put(index,buildDialogMoreChoice(names4, ids4,tv_appointmentType,mSelecteds.get(index),"除授类别"));
                        break;

                    case 4:
                        List<OfficeCategories> list5 = new Gson().fromJson(result, new TypeToken<List<OfficeCategories>>(){}.getType());
                        int listSize5 = list5.size();
                        String[] names5 = new String[listSize5];
                        int[] ids5 = new int[listSize5];
                        for (int i = 0; i <listSize5 ; i++) {
                            names5[i] = list5.get(i).getcCategoryDescChn();
                            ids5[i] = list5.get(i).getcOfficeCategoryId();
                        }
                        mDialogs.put(index,buildDialogMoreChoice(names5, ids5,tv_offCategory,mSelecteds.get(index),"职官类别"));
                        break;

                    case 5:
                        List<BiogInstCodes> list6 = new Gson().fromJson(result, new TypeToken<List<BiogInstCodes>>(){}.getType());
                        int listSize6 = list6.size();
                        String[] names6 = new String[listSize6];
                        int[] ids6 = new int[listSize6];
                        for (int i = 0; i <listSize6 ; i++) {
                            names6[i] = list6.get(i).getcBiRoleChn();
                            ids6[i] = list6.get(i).getcBiRoleCode();
                        }
                        mDialogs.put(index,buildDialogMoreChoice(names6, ids6,tv_biogInst,mSelecteds.get(index),"社交角色"));
                        break;
                    case 6:
                        List<TextRoleCodes> list7 = new Gson().fromJson(result, new TypeToken<List<TextRoleCodes>>(){}.getType());
                        String[] names = new String[list7.size()+1];
                        final String[] ids = new String[list7.size()+1];
                        names[0] = "请选择";
                        int i = 1;
                        for (TextRoleCodes code: list7) {
                            names[i] = code.getcRoleDescChn();
                            ids[i] = code.getcRoleId()+"";
                            i++;
                        }
                        ArrayAdapter<String> adapter = new ArrayAdapter<>(mContext, R.layout.support_simple_spinner_dropdown_item, names);
                        sp_textRole.setAdapter(adapter);
                        sp_textRole.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                                if (i != 0) {
                                    mSingleSelectIds[4] = ids[i];
                                }
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> adapterView) {

                            }
                        });
                        break;
                }
            }
            @Override
            public void requestFailure(Request request, IOException e) {
                ToastUtil.showShort(mContext,"请求错误！");
            }
        });
    }

    /**
     * 构造多选dialog
     * @param names
     * @param ids
     * @param tv
     * @param list
     * @param title
     * @return
     */
    private AlertDialog buildDialogMoreChoice(final String[] names, final int[] ids, final TextView tv, final List<Integer> list,String title) {
        final boolean[] selected = new boolean[ids.length];
        for (int i = 0; i < ids.length - 1; i++) {
            selected[i] = false;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(this,3);
        builder.setTitle(title);
        builder.setMultiChoiceItems(names,selected,new DialogInterface.OnMultiChoiceClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which, boolean isChecked) {
            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                list.clear();
                StringBuilder sb = new StringBuilder();
                // android会自动根据选择的改变selected数组的值。
                for (int i = 0; i < selected.length; i++) {
                    if (selected[i]) {
                        sb.append(names[i]);
                        sb.append(",");
                        list.add(ids[i]);
                    }
                }
                if (sb.length() == 0) {
                    tv.setText("");
                }else {
                    tv.setText(sb.toString().substring(0,sb.length()-1));
                }
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int i) {
                dialog.dismiss();
            }
        });
        return builder.create();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.tv_choronym:
                mDialogs.get(0).show();
            break;
            case R.id.tv_dy:
                mDialogs.get(1).show();
                break;
            case R.id.tv_addrType:
                mDialogs.get(2).show();
                break;
            case R.id.tv_appointmentType:
                mDialogs.get(3).show();
                break;
            case R.id.tv_offCategory:
                mDialogs.get(4).show();
                break;
            case R.id.tv_biogInst:
                mDialogs.get(5).show();
                break;
            case R.id.et_enthnicity:
                Intent intent1 = new Intent(mContext,SelectedActivity.class);
                intent1.putExtra("title",Constant.TITLE.TITLE_QETHNICITY);
                intent1.putExtra("tabName",Constant.SVTAB.SV_ETHNICITY_TAB);
                startActivityForResult(intent1,1);
                break;
            case R.id.et_addrName:
                Intent intent2 = new Intent(mContext, X5WebViewActivity.class);
                intent2.putExtra("title",Constant.TITLE.TITLE_QADDR);
                intent2.putExtra("url",Constant.DOMAIN_PROJECT+Constant.HTML.HTML_QSELEADDR);
                startActivityForResult(intent2,2);
                break;
            case R.id.et_officeName:
                Intent intent3 = new Intent(mContext, X5WebViewActivity.class);
                intent3.putExtra("title",Constant.TITLE.TITLE_QOFFICE);
                intent3.putExtra("url",Constant.DOMAIN_PROJECT+Constant.HTML.HTML_QSELEOFFICE);
                startActivityForResult(intent3,3);
                break;
            case R.id.et_entryType:
                Intent intent4 = new Intent(mContext, X5WebViewActivity.class);
                intent4.putExtra("title",Constant.TITLE.TITLE_QENTRYTYPE);
                intent4.putExtra("url",Constant.DOMAIN_PROJECT+Constant.HTML.HTML_QENTRYTYPE);
                startActivityForResult(intent4,4);
                break;
            case R.id.et_institution:
                Intent intent5 = new Intent(mContext,SelectedActivity.class);
                intent5.putExtra("title",Constant.TITLE.TITLE_QINSTITUTION);
                intent5.putExtra("tabName",Constant.SVTAB.SV_INSTITUTION_TAB);
                startActivityForResult(intent5,5);
                break;
            case R.id.et_status:
                Intent intent6 = new Intent(mContext,SelectedActivity.class);
                intent6.putExtra("title",Constant.TITLE.TITLE_QSTATUSCODE);
                intent6.putExtra("tabName",Constant.SVTAB.SV_STATUSCODE_TAB);
                startActivityForResult(intent6,6);
                break;
            case R.id.btn_query:
                sendParams();
                break;
            case R.id.btn_clean:
                break;
        }
    }

    /**
     * 提取查询条件传值
     *
     */
    private void sendParams() {
        Intent intent = new Intent(mContext,SearchActivity.class);
        intent.putExtra("title",Constant.TITLE.TITLE_QADVANCEDQUERY);
        intent.putExtra("isShowSeachView",false);
        intent.putExtra("isFromSelected",true);

        String personName = et_name.getText().toString();
        String textName = et_textName.getText().toString();
        intent.putExtra("personName",personName);
        intent.putExtra("textName",textName);

        int multiSize = mSelecteds.size();
        String[] multiParams = new String[multiSize];
        String[] singleParams = new String[mSingleSelectIds.length];
        for (int i = 0; i < multiSize; i++) {
            multiParams[i] = parseIntList(mSelecteds.get(i));
//            Log.d(TAG,"i:"+i+" "+multiParams[i]);
            if (i < mSingleSelectIds.length){
                singleParams[i] = mSingleSelectIds[i];
            }
        }
        intent.putExtra("multiParams",multiParams);
        intent.putExtra("singleParams",singleParams);
        startActivity(intent);
    }

    private String parseIntList(List<Integer> list){
        if (!StringUtil.isEmpty(list)) {
            StringBuilder sb = new StringBuilder();
            int size = list.size();
            for (int i = 0; i < size; i++) {
                sb.append(list.get(i));
                sb.append(",");
            }
            return sb.substring(0,sb.length()-1);
        }else {
            return null;
        }
    }

}
